package cn.ito.zjgsu.web.controller;


import java.awt.Color;
import java.io.IOException;
import java.net.URLEncoder;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.bingoohuang.patchca.color.SingleColorFactory;
import com.github.bingoohuang.patchca.custom.ConfigurableCaptchaService;
import com.github.bingoohuang.patchca.filter.predefined.CurvesRippleFilterFactory;
import com.github.bingoohuang.patchca.font.RandomFontFactory;
import com.github.bingoohuang.patchca.utils.encoder.EncoderHelper;
import com.github.bingoohuang.patchca.word.RandomWordFactory;
import cn.ito.zjgsu.constant.StatusCode;

@Controller
public class IndexController {
	
	@RequestMapping(value = "/")
	public String index() {
		Subject currentUser = SecurityUtils.getSubject();
		if (currentUser.isAuthenticated()) {
			if(currentUser.hasRole("admin")){
				return "redirect:/depart";
			}
			if(currentUser.hasRole("staff")){
				return "redirect:/staff/";
			}
			return "redirect:/staff/";
		} else {
			return "login";
		}
	}
	
	
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String Login(@RequestParam String username, @RequestParam String password, HttpServletRequest request,
			ModelMap map,HttpServletResponse response) {
		Subject currentUser = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username, password);
		String authticationError = "null";
		try {
			currentUser.login(token);
			Cookie[] cookies = request.getCookies();
		} catch (UnknownAccountException e) {
			authticationError = "用户名错误";
		} catch (IncorrectCredentialsException e) {
			authticationError = "密码错误";
		}
		Cookie cookie = new Cookie("username",username);
		//map.addAttribute("username",username);
		authticationError = URLEncoder.encode(authticationError);
		/*map.addAttribute("error", authticationError);*/
		Cookie error = new Cookie("error", authticationError);
		response.addCookie(cookie);	
		response.addCookie(error);
		System.out.println(authticationError);
		return "redirect:/";

	}
	
	@RequestMapping(value = "/logout", method = RequestMethod.POST)
	@ResponseBody
	public String Logout() {
		String status = StatusCode.FAILURE_STATUS;
		try {
			Subject currentUser = SecurityUtils.getSubject();
			currentUser.logout();
			status = StatusCode.SUCCESS_STATUS;
		} catch (Exception e) {
			status = StatusCode.FAILURE_STATUS;
		}
		return JSON.toJSONString(status);
	}
	
	
	@RequestMapping(value = "/init/RegValCode",method = RequestMethod.GET)
	@ResponseBody
	public String RegValCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String valCode = "";
		try{
			valCode = (String) request.getSession().getAttribute("REG_VAL_CODE");
			System.out.println("valCode="+valCode);
		}catch(Exception e){		
		}
		JSONObject json = new JSONObject();
		json.put("valCode", valCode);
		return json.toJSONString();	
	}
		
	@RequestMapping(value = "/init/InitRegValCode", produces = "text/plain;charset=UTF-8")
	@ResponseBody
	public String InitRegValCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
		ConfigurableCaptchaService cs = new ConfigurableCaptchaService();
		cs.setColorFactory(new SingleColorFactory(new Color(25, 60, 170)));
		cs.setFilterFactory(new CurvesRippleFilterFactory(cs.getColorFactory()));
		RandomFontFactory ff = new RandomFontFactory();
		ff.setMinSize(30);
		ff.setMaxSize(30);
		RandomWordFactory rwf = new RandomWordFactory();
		rwf.setMinLength(4);
		rwf.setMaxLength(4);
		cs.setWordFactory(rwf);
		cs.setFontFactory(ff);
		cs.setHeight(30);
		cs.setWidth(140);
		try {
			HttpSession session = request.getSession();
			ServletOutputStream stream = response.getOutputStream();
			String validate_code = EncoderHelper.getChallangeAndWriteImage(cs, "png", stream);
			session.setAttribute("REG_VAL_CODE", validate_code);
			
			System.out.println(validate_code);
			stream.flush();
			stream.close();
			JSONObject json = new JSONObject();
			
			return json.toJSONString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

/*	@RequestMapping(value = "/insertusertest", method = RequestMethod.GET)
	@ResponseBody
	public void insertUser() {
		UserLogin user = new UserLogin();
		user.setJobId(123);
		user.setNickname("jack");
		user.setPersonId(123124);
		user.setRoleId(3);
		user.setUsername("dhas");
		user.setPassword("111111");

		String status = userService.insertUser(user);

		System.out.println("insertStatus = " + status);
	}

	@RequestMapping(value = "/loginValidate", method = RequestMethod.GET)
	public String submitLoginForm(HttpServletRequest request, Model model) {
		String errorClassName = (String) request.getAttribute("shiroLoginFailure");
		String authticationError = null;
		if (UnknownAccountException.class.getName().equals(errorClassName)) {
			authticationError = "用户名/密码错误";
		} else if (IncorrectCredentialsException.class.getName().equals(errorClassName)) {
			authticationError = "用户名/密码错误";
		} else if (errorClassName != null) {
			authticationError = "未知错误：" + errorClassName;
		}
		model.addAttribute("authticationError", authticationError);
		return "myindex2";
	}

	@RequestMapping(value = "/testDepartment", method = RequestMethod.GET)
	@ResponseBody
	public void testDepartment() {
		List<DepartmentWrapper> ldw = departmentService.initDepartmentTree();
		//System.out.println(ldw.toString());
		System.out.println(DepartmentWrapper.toJsonArrayString(ldw));
	}*/
}
